import socket
from kThreadFile import KThread as KTH
from deepseekClientPostAnswerFile import  deepseekClientPostAnswer as DSCPA
from toolFile import Tool
# from deepseekClientPostAnswerFile import deepseekClientPostAnswer as DSCPA
class server:
    sip = "127.0.0.1"
    sport = 12476
    smaxThreadCount = 20;
    threadID=1
    maxReceviedSize=1024
    # sthreadPool=None
    def setMaxThreadCount(self, i):
        self.maxThreadCount = i

    def __init__(self, threadPool, maxListenCount):
        self.tcp_Server_socket = None
        print("a server class has been built")
        # self.deepseekClientPostTest=
        self.sthreadPool = threadPool
        # print( )
        self.setMaxThreadCount(maxListenCount)
        self.startBuildingConnection(ip=self.sip, port=self.sport)


    def handlefunc(self,client_socket):
        deepseekClientPostAnswerFile=DSCPA()
        tool=Tool()
        with client_socket:
            while True:
                try:
                    data = client_socket.recv(self.maxReceviedSize)
                    if not data: break
                    print(data.decode("utf-8"))
                    # backdata=deepseekClientPostAnswerFile.postToDeepSeekCom(promot=(data.decode("utf-8")))
                    buffer = bytearray()
                    response_stream = deepseekClientPostAnswerFile.postToDeepSeek(promot=data.decode("utf-8"), deepseekv=2,isstream=True, deepthought=True)


                    if response_stream is not None:
                        buffer = bytearray()
                        chunk_counter = 1
                        for chunk in response_stream:
                            if chunk:
                                buffer.extend(chunk)
                                client_socket.sendall(f"Echo[{chunk_counter}]:".encode() + chunk)
                                chunk_counter += 1
                        print("Full response:", buffer.decode('utf-8'))
                    else:
                        print("Error: Received empty response stream")
                        client_socket.sendall(b"Error: Empty response from API")
                except ConnectionResetError:
                    print("连接中断")
                    break


    def startBuildingConnection(self, ip, port, threadID=None):
        self.tcp_Server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_Server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.tcp_Server_socket.bind((ip, port))
        self.tcp_Server_socket.listen(self.smaxThreadCount)
        # print("tcccccc")
        while True:
            # print("123abc")
            client_socket,port = self.tcp_Server_socket.accept()
            # print("connected")
            clientHadnleThread=KTH(threadID=self.threadID,counter=1,name="client-socket-con",debugMode=True,needpool=True)
            # clientHadnleThread = KTH(1, "testthread", 123, debugMode=True, needpool=True)

            clientHadnleThread.setfunc(func=self.handlefunc,args=client_socket,isHadArgs=True)

            self.sthreadPool.pushThreadsAndStart(thread= clientHadnleThread)
            # print("123")
            self.threadID+=1
        # print("break while")
        # client_socket,port=tcp_Server_socket.accept()
